package com.zzh.tree;

import java.util.*;

public class No107_levelOrderBottom {
    public static void main(String[] args) {
        No107Solution solution = new No107Solution();
        List<List<Integer>> lists = solution.levelOrderBottom(TreeNode.initTree());
        for (List list : lists) {
            System.out.println(Arrays.toString(list.toArray()));
        }
    }
}

class No107Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return new LinkedList<>();
        }
        LinkedList<List<Integer>> lists = new LinkedList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            int size = q.size();
            ArrayList<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                temp.add(cur.val);
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            lists.addFirst(temp);
        }
        return lists;
    }
}
